package com.RequestGongWuShu;

import java.io.File;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.requestGwsLongGangQu.GwsLgqUtil;
import com.yishun.springboot.mapper.TspDetailedMapper;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 塔式起重机设备对接测试 注：方法上的注释打√的方法为对接测试环境已通过
 *
 * @author YS
 * @date 2020/12/04 16:58
 */

@Slf4j
public class Crane {

	@Autowired
	TspDetailedMapper tspDetailedMapper;

	private static String api_key = "247ac03f3e4346628dace41e52253dc3";
	private static String api_version = "1.0";
	private static String engCode = "HG003254";// 工程编号
	private static String projectCode = "XM20210823";// 项目编号
	private static String baseUlr = "http://szwb.sz.gov.cn:2018/openapi";// 请求地址

	/**
	 * 2.3.1上报塔式起重机基本信息√
	 */
	public void addBasicInfo() {

		String url = baseUlr + "/crane/addBasicInfo";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		JSONObject json = new JSONObject();
		StringBuffer photosParam1 = new StringBuffer("ffbe6ac3b17f5a457cbd1a7abfe2ff1e");
		List<Object> photosList = new ArrayList<>();
		json.put("device_no", "7986207e559b45a3ab62611c28153550");
		// json.put("model", "9527牌照国标");
		json.put("name", "16#塔式起重机");
		json.put("uid", "09式狙击步枪");
		json.put("license", "2020-09-11");
		json.put("license_start_date", "2020-09-11");
		json.put("license_end_date", "2050-09-11");
		json.put("property_unit", "什么产权单位？没有的事");
		json.put("mnufacturer_business", "国标水神共工");
		json.put("mai_war_bus", "大锅饭维保商");
		json.put("testing_business", "检测商监测啥");
		json.put("in_date", "2020-12-04");
		json.put("out_date", "2020-12-09");
		json.put("mon_device_man", "真多参数-监测设备厂商");
		json.put("device_installation_date", "2020-07-06");
		json.put("guangdong_install_num", "粤BE-S03981");

		photosList.add(photosParam1);
		json.put("photos", photosList);

		String body = JSON.toJSONString(json);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		String a = GwsLgqUtil.GwsParamUtil(json, timestamp, signature, api_key, projectCode, engCode, api_version);

		log.info("All:" + a);
		String info = HttpUtil.post(url, a);
		log.info("down!" + info);
	}

	public String addBasicInfo(JSONObject paramJson) {
		String url = baseUlr + "/crane/addBasicInfo";

		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		String body = JSON.toJSONString(paramJson);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		JSONObject param = new JSONObject();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		param.put("body", paramJson);
		param.put("signature", signature);

		String paramJsonStr = param.toJSONString();

		log.info("参数：" + paramJsonStr);

		String info = HttpUtil.post(url, paramJsonStr);

		return info;
	}

	/**
	 * 2.3.2上报塔式起重机参数信息√
	 */
	public void addParams() {
		String url = baseUlr + "/crane/addParams";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		JSONObject json = new JSONObject();

		json.put("device_no", "7986207e559b45a3ab62611c28153549");
		json.put("model", "随便起名字型号看看");
		json.put("name", "随便起名字看看");
		json.put("TC_MaxScope", 0);
		json.put("TC_SB_SpeedCut", 32.2);
		json.put("TC_SA_SpeedCut", 33.2);
		json.put("TC_MaxHeight", 35.6);
		json.put("TC_MAX_XB_HEIGHT", 34.1);
		json.put("TC_MinHeight", 29.3);
		json.put("TC_HU_SpeedCut", 23.0);
		json.put("TC_MinScope", 14.2);
		json.put("TC_HB_SpeedCut", 14.2);
		json.put("TC_LoadCapacity", 1420);
		json.put("TC_MS_LoadCapacity", 1420);

		json.put("TC_ML_MaxScope", 14.2);
		json.put("TC_Multiple", 3.3);
		json.put("Tower_type", 0);
		json.put("load_moment", 2.3);

		String body = JSON.toJSONString(json);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		String a = GwsLgqUtil.GwsParamUtil(json, timestamp, signature, api_key, projectCode, engCode, api_version);

		log.info("All:" + a);
		String info = HttpUtil.post(url, a);
		log.info("down!" + info);
	}

	/**
	 * 2.3.6上报塔机通电时间接口√
	 */
	public void electrify() {
		String url = baseUlr + "/crane/electrify";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		List<Object> array = new ArrayList<>();
		JSONObject json = new JSONObject();

		json.put("device_no", "7986207e559b45a3ab62611c28153549");
		json.put("runtime", "2020-12-01 17:23:05");
		json.put("operation", 0);
		array.add(json); // 内容格式不正确，最后给到签名生成的方法也会不通过服务器端的验证，故而出现message":"校验失败","detailMessage":"无效签名",
		// 这个未通过测试，格式有待看文档做好

		String body = JSONArray.toJSONString(array); // 该处好像是签名生成方法一定要变成json，至于真正请求的请求体则是该是文档什么样子就是什么样子，这一点在文档好像并沒有明确提到！

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		param.put("body", array);
		param.put("signature", signature);
		JSONObject json2 = new JSONObject(param);
		String a = json2.toJSONString();

		log.info("All:" + a);
		String info = HttpUtil.post(url, a);
		log.info("down!" + info);
	}

	public static JSONObject electrify(JSONObject json) {

		String url = baseUlr + "/crane/electrify";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		JSONArray arrayParam = new JSONArray();
		arrayParam.add(json);

		String body = JSONArray.toJSONString(arrayParam);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		JSONObject param = new JSONObject();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		param.put("body", arrayParam);
		param.put("signature", signature);

		String paramStr = param.toJSONString();

		log.info("All:" + paramStr);

		String info = HttpUtil.post(url, paramStr);

		JSONObject resJsonObject = JSONObject.parseObject(info);

		return resJsonObject;
	}

	/**
	 * 2.3.7上报塔机机司机打卡记录信息√
	 */

	public void clockIn() {
		String url = baseUlr + "/crane/clockIn";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		List<Object> array = new ArrayList<>();
		JSONObject json = new JSONObject();

		json.put("device_no", "7986207e559b45a3ab62611c28153549");
		json.put("worker_name", "小发");
		json.put("start_time", "2020-12-01 10:23:05");
		json.put("end_time", "2020-12-01 17:23:05");
		array.add(json);

		String body = JSONArray.toJSONString(array);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		param.put("body", array);
		param.put("signature", signature);
		JSONObject json2 = new JSONObject(param);
		String a = json2.toJSONString();

		log.info("All:" + a);
		String info = HttpUtil.post(url, a);
		log.info("down!" + info);
	}

	/**
	 * 2.3.5上报塔机工作循环数据√
	 */
	public void workLoop() {

		// 这个上报塔机工作循环数据
		// 心累，同样的东西，上去拿拿这边拿拿那里碰碰又可以了，心累。同样的格式之前一直不行，整着整着又可以了...搞不懂这格式是不是服务器临时变动了端口？
		String url = baseUlr + "/crane/workLoop";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		List<Object> array = new ArrayList<>();
		JSONObject json = new JSONObject();

		json.put("device_no", "7986207e559b45a3ab62611c28153549");
		json.put("start_time", "2020-12-01 10:23:05");
		json.put("end_time", "2020-12-01 10:24:07");
		json.put("max_moment_ratio", 0.8);
		json.put("exceeding_num", 1.0);
		json.put("max_wind_speed", 0.18);
		json.put("is_over_wind_speed", 1);
		json.put("max_range", 23.0);
		json.put("max_height", 23.0);
		array.add(json);

		String body = JSONArray.toJSONString(array);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		param.put("body", array);
		param.put("signature", signature);
		JSONObject json2 = new JSONObject(param);
		String a = json2.toJSONString();

		log.info("All:" + a);
		String info = HttpUtil.post(url, a);
		log.info("down!" + info);
	}

	public static JSONObject workLoop(JSONObject jsonParam) {

		String url = baseUlr + "/crane/workLoop";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		// 因为需要数组格式，所以需要用array装起来，但是用array也只能一条。。。。大大的问题
		JSONArray array = new JSONArray();
		array.add(jsonParam);

		String body = JSONArray.toJSONString(array);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		JSONObject param = new JSONObject();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		param.put("body", array);
		param.put("signature", signature);

		String paramStr = param.toJSONString();

		log.info("All:" + paramStr);

		String info = HttpUtil.post(url, paramStr);

		JSONObject resJsonObject = JSONObject.parseObject(info);

		return resJsonObject;

	}

	public static void main(String[] args) {
		workLoop(null);
	}

	/**
	 * 2.3.3上报塔式起重机实时数据√ 可能是工务署服务器有人在改动端口，我测试的时候，这个前面可以后面,也就是现在又不可以了... 12-04
	 * 19:48
	 */
	public void addRecord() {
		String url = baseUlr + "/crane/addRecord";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		List<Object> array = new ArrayList<>();
		JSONObject json = new JSONObject();

		json.put("device_no", "7986207e559b45a3ab62611c28153550");
		json.put("runtime", "2020-12-01 10:23:05");
		json.put("load", 99.0);
		json.put("load_ratio", 0.8);
		json.put("moment", 23.0);
		json.put("moment_ratio", 0.8);
		json.put("slewing_speed", 26.7);

		json.put("is_left_warning", 1);
		json.put("is_right_warning", 1);
		json.put("range", 1.0);
		json.put("is_forward_warning", 1);
		json.put("is_backward_warning", 1);
		json.put("height", 6.7);
		json.put("is_up_warning", 0);
		// json.put("magnification", 3); // 这里的参数文档类型是Double，实际是Int才不会报错
		// json.put("work_environment", 3); //这里的参数文档类型是Double，实际是Int才不会报错
		json.put("real_time_flag", 1);

		json.put("installation_method", 1);
		json.put("wind_speed", 0.2);
		json.put("collision_warn", 0);
		json.put("wind_warn", 0);
		json.put("rotation_warn", 0);
		json.put("card_num", "6545414511");
		json.put("operator_name", "test");

		array.add(json);

		String body = JSONArray.toJSONString(array);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		param.put("body", array);
		param.put("signature", signature);
		JSONObject json2 = new JSONObject(param);
		String a = json2.toJSONString();

		log.info("All:" + a);
		String info = HttpUtil.post(url, a);
		log.info("down!" + info);

	}

	/**
	 * 2.3.42.3.4上报塔机预警数据 √
	 */

	public void warning() {
		String url = baseUlr + "/crane/warning";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		List<Object> array = new ArrayList<>();
		JSONObject json = new JSONObject();

		json.put("device_no", "7986207e559b45a3ab62611c28153549");
		json.put("runtime", "2020-12-01 10:23:05");
		json.put("load", 99.0);
		json.put("load_ratio", 0.8);
		json.put("moment", 23.0);
		json.put("moment_ratio", 0.8);
		json.put("slewing_speed", 26.7);

		json.put("height", 5.0);
		json.put("range", 23.1);
		json.put("magnification", 1);
		json.put("sensor_status", 1);
		json.put("normal_work_early_warn_state", 1);
		json.put("normal_work_warn_status", 1);
		json.put("region_limit_early_warn_status", 1);
		json.put("region_limit_warn_status", 1);
		json.put("group_tower_early_warn_status", 1);
		json.put("group_tower_warn_status", 1);
		json.put("wind_speed", 0.2);

		array.add(json);

		String body = JSONArray.toJSONString(array);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		param.put("body", array);
		param.put("signature", signature);
		JSONObject json2 = new JSONObject(param);
		String a = json2.toJSONString();

		log.info("All:" + a);
		String info = HttpUtil.post(url, a);
		log.info("down!" + info);
	}

	/**
	 * 硬件通用上传图片√
	 */
	public void uploadImage() {
		HashMap<String, Object> paramMap = new HashMap<>();
		// 文件
		File file = new File("C:\\Users\\YS\\Desktop\\downloadImgToWebSiteWeiChat\\timg.jpg");
		paramMap.put("file", file);
		paramMap.put("api_key", api_key);
		String result = HttpUtil.post("https://szwb.sz.gov.cn:2019/uploadfile-openpai/uploadImage", paramMap);
		log.info(result);// 返回文件的id
		// resultData":"ffbe6ac3b17f5a457cbd1a7abfe2ff1e"
	}

	public static void setApi_key(String api_key) {
		Crane.api_key = api_key;
	}

	public static void setApi_version(String api_version) {
		Crane.api_version = api_version;
	}

	public static void setEngCode(String engCode) {
		Crane.engCode = engCode;
	}

	public static void setProjectCode(String projectCode) {
		Crane.projectCode = projectCode;
	}

	/**
	 * 获取签名
	 *
	 * @param: [apiKey,
	 *             apiVersion, engCode, projectCode, timestamp, body]
	 * @return: java.lang.String
	 */
	public static String getSignature(String apiKey, String apiVersion, String engCode, String projectCode,
			String timestamp, String body) {
		String str4MD5 = String.format("api_key%sapi_version%sbody%seng_code=%sproject_code=%stimestamp%s", apiKey,
				apiVersion, body.isEmpty() ? "{}" : body, engCode, projectCode, timestamp);
		return getMD5Code(str4MD5);
	}

	public static String getMD5Code(String strObj) {
		String resultString = null;
		try {
			resultString = new String(strObj);
			MessageDigest md = MessageDigest.getInstance("MD5");
			Charset charset = Charset.forName("UTF-8");
			resultString = byteToString(md.digest(strObj.getBytes(charset)));
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return resultString;
	}

	// 转换字节数组为16进制字串
	private static String byteToString(byte[] bByte) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < bByte.length; i++) {
			sBuffer.append(byteToArrayString(bByte[i]));
		}
		return sBuffer.toString();
	}

	private static String byteToArrayString(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	// 全局数组
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
			"E", "F" };

}
